#include <WiFi.h>
#include <ESPAsyncWebServer.h>
#include <ArduinoJson.h>

// 替换为你的 WiFi 名称和密码
const char* ssid = "YOUR_SSID";
const char* password = "YOUR_PASSWORD";

AsyncWebServer server(80);
AsyncWebSocket ws("/ws");

// === HTML 页面内容（嵌入）===
const char index_html[] PROGMEM = R"rawliteral(
<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>ESP32-S3 Robot Control</title>
    <style>
        body { font-family: Arial; text-align: center; margin-top: 50px; }
        button { width: 80px; height: 80px; font-size: 24px; margin: 10px; }
    </style>
</head>
<body>
    <h1>ESP32-S3 履带小车控制</h1>
    <button onclick="send('forward')">↑</button><br>
    <button onclick="send('left')">←</button>
    <button onclick="send('stop')">●</button>
    <button onclick="send('right')">→</button><br>
    <button onclick="send('backward')">↓</button><br><br>
    <div id="status">等待连接...</div>

    <script>
        const ws = new WebSocket('ws://' + location.hostname + ':80/ws');
        ws.onmessage = function(event) {
            document.getElementById("status").innerText = event.data;
        };

        function send(cmd) {
            ws.send(cmd);
        }
    </script>
</body>
</html>
)rawliteral";

// === 处理根目录请求 ===
void handleRoot(AsyncWebServerRequest *request) {
    request->send_P(200, "text/html", index_html);
}

// === WebSocket 事件处理 ===
void onEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, 
             AwsEventType type, void *arg, uint8_t *data, size_t len) {
    if (type == WS_EVT_DATA) {
        AwsFrameInfo *info = (AwsFrameInfo*)arg;
        if (info->final && info->index == 0 && info->len == len) {
            String cmd = "";
            for(size_t i=0; i < len; i++) {
                cmd += (char)data[i];
            }

            // 处理命令（示例：发送给电机模块）
            if (cmd == "forward") {
                Serial.println("Command: Forward");
                // motor_forward();
            } else if (cmd == "backward") {
                Serial.println("Command: Backward");
                // motor_backward();
            } else if (cmd == "left") {
                Serial.println("Command: Left");
                // motor_left();
            } else if (cmd == "right") {
                Serial.println("Command: Right");
                // motor_right();
            } else if (cmd == "stop") {
                Serial.println("Command: Stop");
                // motor_stop();
            }

            // 广播状态（可以是传感器数据）
            String status = "CMD: " + cmd;
            client->send(status.c_str());
        }
    }
}

// === 初始化 WebSocket ===
void initWebSocket() {
    ws.onEvent(onEvent);
    server.addHandler(&ws);
}

// === 初始化电机控制（示例函数）===
void setupMotorControl() {
    // pinMode(IN1, OUTPUT); ...
    // digitalWrite(IN1, LOW); ...
    Serial.println("Motor control initialized.");
}

// === SETUP ===
void setup() {
    Serial.begin(115200);

    WiFi.begin(ssid, password);
    while (WiFi.status() != WL_CONNECTED) {
        delay(1000);
        Serial.println("Connecting to WiFi...");
    }

    Serial.println("Connected to WiFi");
    Serial.print("IP Address: ");
    Serial.println(WiFi.localIP());

    setupMotorControl();

    initWebSocket();
    server.on("/", handleRoot);
    server.begin();
}

// === LOOP ===
void loop() {
    // 主循环可处理传感器读取、自动避障等逻辑
    ws.cleanupClients(); // 清理断开的客户端
    delay(100);
}